package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WxAppConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.utils.sign.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;


public class WechatUtils {
    @Value("${wx-app.appId}")
    private String appId;

    @Value("${wx-app.appSecret}")
    private String appSecret;

    private final RestTemplate restTemplate = new RestTemplate();

    public String getOpenId(String code, String appid, String appSecret) {
        String accessUrl = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appid, appSecret, code);
        String resOpen = restTemplate.getForObject(accessUrl, String.class);
        JSONObject jsonObjectOpen = JSONObject.parseObject(resOpen);
        if (jsonObjectOpen.get("errcode") != null)
            System.out.println(jsonObjectOpen.get("errcode").toString() + ":" + jsonObjectOpen.get("errmsg"));
        String accessToken = jsonObjectOpen.getString("access_token");
        return jsonObjectOpen.getString("openid");
    }

    public JSONObject getPhoneNumberJson(String code, String encryptedIv, String encryptedData, String appid, String appSecret) throws Exception {
        WxAppConfig wxAppConfig = new WxAppConfig();
        System.out.println("appId:" + appid);
        System.out.println("appSecret:" + wxAppConfig.getAppId());
        //向微信服务器发送恳求获取用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        System.out.println("jsonObject:" + jsonObject.toString());
        // 获取session_key和openid
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openid");
        String decryptResult = "";
        decryptResult = decrypt(sessionKey, encryptedIv, encryptedData);
        JSONObject resultJsonObject = JSONObject.parseObject(decryptResult);
        resultJsonObject.put("openId", openId);
        return resultJsonObject;
    }

    public String getAccessToken(String appid, String appSecret) {
        String url = "https://api.weixin.qq.com/cgi-bin/toke?grant_type=client_credential&appid=" + appid + "&secret=" + appSecret;
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        String accessToken = jsonObject.getString("access_token");
        String expiresIn = jsonObject.getString("expires_in");
        return accessToken;
    }

    public String pushMessage(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token" + accessToken;
        return "";
    }

    private String decrypt(String sessionKey, String encryptedIv, String encryptedData) throws Exception {
        // 转化为字节数组
        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIv);
        byte[] encData = Base64.decode(encryptedData);
        // 假如密钥缺乏16位，那么就补足
        int base = 16;
        if (key.length % base != 0) {
            int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(key, 0, temp, 0, key.length);
            key = temp;
        }
        // 假如初始向量缺乏16位，也补足
        if (iv.length % base != 0) {
            int groups = iv.length / base + (iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(iv, 0, temp, 0, iv.length);
            iv = temp;
        }
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultStr = new String(cipher.doFinal(encData), "UTF-8");
        } catch (Exception e) {
            //            logger.info("解析错误");
            e.printStackTrace();
        }
        // 解析加密后的字符串
        return resultStr;
    }
}
